package tool

import java.io.File
import java.net.URLEncoder
import java.nio.file.Files

import dao.ModeDao
import org.joda.time.DateTime
import play.api.libs.Files.TemporaryFile
import play.api.mvc.{MultipartFormData, Request, RequestHeader}
import utils.{DesEncrypter, Utils}


/**
 * Created by yz on 3/7/2020
 */
object Tool extends ProjectTool{

  val registerDesEncrypter = new DesEncrypter("register12345678")
  val newPasswordDesEncrypter = new DesEncrypter("newPassword12345")
  val playPath = new File("../").getAbsolutePath
  val windowsTestDir = new File("C:\\temp")
  val linuxTestDir = new File(playPath, "workspace")
  val testDir = if (windowsTestDir.exists()) windowsTestDir else linuxTestDir
  val dbName = "mole_pathology_database"
  val projectName = "mole_pathology_scala_js"
  val windowsPath = s"C:\\${dbName}"
  val linuxPath = playPath + s"/${dbName}"
  val path = {
    if (new File(windowsPath).exists()) windowsPath else linuxPath
  }
  val userDir = new File(path, "user")
  val dataDir = new File(path, "data")
  val exampleDir = new File(path, "example")
  val softExampleDir = new File(exampleDir, "soft")
  val dataAvatarDir = new File(dataDir, "avatar")

  val rPath = {
    val rPath = s"C:\\workspaceForIDEA\\${projectName}\\server\\rScripts"
    val linuxRPath = linuxPath + "/rScripts"
    if (new File(rPath).exists()) rPath else linuxRPath
  }

  def generateMissionName = {
    (new DateTime).toString("yyyyMMddHHmmss")
  }

  def getUserId(implicit request: RequestHeader) = {
    request.session.get("id").get.toInt
  }

  def fileMoveDir(fieldName: String, dir: File)(implicit request: Request[MultipartFormData[TemporaryFile]]) = {
    fileMoveDirOp(fieldName, dir).get
  }

  def fileMoveDirOp(fieldName: String, dir: File)(implicit request: Request[MultipartFormData[TemporaryFile]]) = {
    val tempFile = request.body.file(fieldName).get
    if (tempFile.ref.path.toFile.length() > 0) {
      val destFile = new File(dir, tempFile.filename)
      tempFile.ref.moveTo(destFile, replace = true)
      Some(destFile)
    } else None
  }

  def createTempDirectory(prefix: String)(implicit modeDao: ModeDao) = {
    if (isTestMode) Tool.testDir else Files.createTempDirectory(prefix).toFile
  }

  def isTestMode(implicit modeDao: ModeDao) = {
    val mode = Utils.execFuture(modeDao.select)
    if (mode.test == "t") true else false
  }

  def deleteDirectory(direcotry: File)(implicit modeDao: ModeDao) = {
    if (!isTestMode) Utils.deleteDirectory(direcotry)
  }

  def urlEncode(url: String) = {
    URLEncoder.encode(url, "UTF-8")
  }

  def getContentDisposition(url: String) = {
    val encodeUrl = Tool.urlEncode(url)
    s"attachment; filename*=utf-8''${encodeUrl}"
  }


}
